package by.jabbby.dataprovider;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import by.jabbby.Logger;

public class ContactProvider {
	public class ContactEntry {
		private long id;
		private String jid;

		public ContactEntry() {

		}

		public ContactEntry(long id, String jid) {
			this.id = id;
			this.jid = jid;
		}

		public long getId() {
			return id;
		}

		public void setId(long id) {
			this.id = id;
		}

		public String getJid() {
			return jid;
		}

		public void setJid(String jid) {
			this.jid = jid;
		}

	}

	private Context context;

	public ContactProvider(Context context) {
		this.context = context;
	}

	public ContactEntry CreateNewEntry(String jid) {
		
		ContactEntry result = null;
		try{
		Dictionary dbHelper = new Dictionary(context);
		SQLiteDatabase db  = dbHelper.getWritableDatabase();
		
		 ContentValues values = new ContentValues();  
		 values.put(Dictionary.T_CONT_JID, jid);  
		 long id  = db.insert(Dictionary.TABLE_CONTACT, null, values);
			if(id !=-1){
			result = new ContactEntry(id, jid);
			Logger.i("Contacprovider: create Contact with jid '" + jid + "' ");
			}else{
				Logger.e("Contacprovider: can not create Contact with jid '" + jid + "'. return null ");
			}
			
		
		} catch (Exception e) {
			Logger.e("Contacprovider: can not create Contact with jid '" + jid + "' ",e);
		}
		return result;

	}

	public ContactEntry getEntry(String jid) {
		ContactEntry result = null;

		Dictionary dbHelper = new Dictionary(context);
		Cursor c = dbHelper.getReadableDatabase().query(Dictionary.TABLE_CONTACT, new String[] { Dictionary.T_CONT_ID },
				"select from " + Dictionary.TABLE_CONTACT + " where " + Dictionary.T_CONT_JID + " = ?", new String[] { jid }, null, null, null);
		if (c.getCount() > 0) {
			int id = c.getInt(0);
			result = new ContactEntry(id, jid);
		} else {
			Logger.i("Contacprovider: Contact with jid '" + jid + "' does not exist");
		}
		return result;
	}

	public ContactEntry getEntryOrCreate(String jid) {
		ContactEntry ce  =getEntry(jid);
		if(ce==null){
			ce = CreateNewEntry(jid);
		}
		return ce;
	}

}
